package com.ohuang.util_h.replaceActivity;

import android.app.Activity;
import android.content.Intent;

public class SuperNameHandleIntent implements HandleIntent {

    String mSuperClassName;
    String newClassName;

    public boolean enable = false;

    public SuperNameHandleIntent(String superClassName, String newName) {
        try {
            Class<?> clazzsuperClassName = Class.forName(superClassName);
            Class<?> clazz = Class.forName(newName);
            newClassName = newName;
            mSuperClassName = superClassName;
            if (!newClassName.equals(superClassName)) {
                enable = true;
            }
        } catch (ClassNotFoundException e) {

        }

    }

    @Override
    public boolean onIntent(Intent intent) {
        try {
            if (enable) {
                String className = intent.getComponent().getClassName();
                String packageName = intent.getComponent().getPackageName();
                if (isSuperClass(className, mSuperClassName)) {
                    intent.setClassName(packageName, newClassName);
                    return true;
                }
            }
        } catch (Throwable e) {

        }

        return false;
    }


    boolean isSuperClass(String className, String superClassName) {
        try {
            if(className.equals(superClassName)){
                return true;
            }
            Class<?> clazz = Class.forName(className);
            Class<?> superClazz = clazz.getSuperclass();
            while (superClazz != null && superClazz != Object.class) {
                if (superClazz.getName().equals(superClassName)) {
                    return true;
                }
                superClazz = superClazz.getSuperclass();
            }
        } catch (Throwable e) {

        }
        return false;
    }
}
